package cn.uikit.demo.other

import android.content.ContentValues
import android.content.Context
import android.content.Intent
import android.graphics.Bitmap
import android.net.Uri
import android.os.Build
import android.os.Environment
import android.provider.MediaStore
import android.text.format.DateUtils
import java.io.File
import java.io.FileOutputStream


object ImageUtil {

    private const val BITMAP_FILE_DIRECTORY = "littlelights"

    fun saveImageToGallery(context: Context, imageName: String, bitmap: Bitmap): Boolean {
        return if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) {
            saveImageToGalleryLow(context, imageName, bitmap)
        } else {
            saveImageToGalleryQ(context, imageName, bitmap)
        }
    }

    /**
     * Android 10 以下版本：
     * 需要 READ_EXTERNAL_STORAGE 和 WRITE_EXTERNAL_STORAGE权限来访问外部存储的公共目录。
     */
    private fun saveImageToGalleryLow(
        context: Context,
        imageName: String,
        bitmap: Bitmap
    ): Boolean {
        val storePath: String = getBitmapFileDir()
        val appDir = File(storePath)
        if (!appDir.exists()) {
            appDir.mkdir()
        }
        val file = File(appDir, imageName)
        try {
            FileOutputStream(file).use { fos ->
                val isSuccess = bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos)
                val uri = Uri.fromFile(file)
                context.sendBroadcast(Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri))
                return isSuccess
            }
        } catch (_: Exception) {
        }
        return false
    }

    private fun saveImageToGalleryQ(context: Context, imageName: String, bitmap: Bitmap): Boolean {
        val imageTime = System.currentTimeMillis()
        val values = ContentValues()
        //在 Android 10 及以上版本，可以指定文件存储在 Pictures 或 Downloads 等标准目录下
        values.put(MediaStore.MediaColumns.RELATIVE_PATH, getBitmapFileDir())
        values.put(MediaStore.MediaColumns.DISPLAY_NAME, imageName)
        values.put(MediaStore.MediaColumns.MIME_TYPE, "image/jpeg")
        values.put(MediaStore.MediaColumns.DATE_ADDED, imageTime / 1000)
        values.put(MediaStore.MediaColumns.DATE_MODIFIED, imageTime / 1000)
        values.put(
            MediaStore.MediaColumns.DATE_EXPIRES,
            (imageTime + DateUtils.DAY_IN_MILLIS) / 1000
        )
        values.put(MediaStore.MediaColumns.IS_PENDING, 1)
        val resolver = context.contentResolver
        resolver.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values)?.let { uri: Uri ->
            try {
                resolver.openOutputStream(uri)?.use { outStream ->
                    if (!bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outStream)) {
                        return false
                    }
                    values.clear()
                    values.put(MediaStore.MediaColumns.IS_PENDING, 0)
                    values.putNull(MediaStore.MediaColumns.DATE_EXPIRES)
                    resolver.update(uri, values, null, null)
                    return true
                }
            } catch (_: Exception) {
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
                    resolver.delete(uri, null)
                }
                return false
            }
        }
        return false
    }

    private fun getBitmapFileDir(): String {
        return if (Build.VERSION.SDK_INT < Build.VERSION_CODES.Q) {
            // android 10 以下版本
            Environment.getExternalStorageDirectory().absolutePath + File.separator + BITMAP_FILE_DIRECTORY
        } else {
            Environment.DIRECTORY_DCIM + File.separator + BITMAP_FILE_DIRECTORY
        }
    }
}